package com.huangd.platform.common.utils;

import com.huangd.platform.common.exception.RRException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

import java.io.*;

public class BigFileUtils {

	public static void eachLine(File file, BigFileLineExecution execution) {
		LineIterator iterator = null;
		try {
			iterator = IOUtils.lineIterator(new BufferedReader(new FileReader(file)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RRException("查询日志出错");
		}
		while (iterator.hasNext()) {
			String line = iterator.nextLine();
			if (Utils.isEmpty(line))
				continue;

			if (!execution.execute(line))
				break;
		}
		iterator.close();
	}

	public static void eachLineReverse(File file, BigFileLineExecution execution) throws Exception {
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile(file, "r");
			long fileLength = rf.length();
			long start = rf.getFilePointer();
			long readIndex = start + fileLength - 1;
			rf.seek(readIndex);
			int c = -1;
			while (readIndex >= start) {
				c = rf.read();
				String line = null;
				boolean newline = c == '\n' || c == '\r';
				if (readIndex == 0 || newline) {
					if (readIndex == 0 && !newline)
						rf.seek(0);

					line = rf.readLine();
					if (line != null) {
						line = new String(line.getBytes("ISO-8859-1"), "utf8");
					} else {
						line = "";
					}

					if (!execution.execute(line))
						break;

					if (readIndex == 0 && newline) {
						if (!execution.execute(""))
							break;
					}

					if (readIndex == 0)
						break;

					if (c == '\n') {
						rf.seek(readIndex - 1);
						int cb = rf.read();
						if (cb == '\r')
							--readIndex;
					}
				}

				--readIndex;
				rf.seek(readIndex);
			}
		} finally {
			com.huangd.platform.common.utils.IOUtils.close(rf);
		}
	}
}
